<template>
  <div class="goods-list-page">
    <h2>商品搜索结果</h2>

    <!-- 搜索栏和返回按钮 -->
    <div class="search-bar">
      <el-button @click="goToShopping" type="primary" icon="ArrowLeft" class="back-button">
        返回商品页面
      </el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="请输入商品名称"
          class="search-input"
          @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 商品列表区域 -->
    <div class="goods-list-container">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else-if="goodsList.length === 0" class="empty">未找到相关商品</div>
      <div v-else class="goods-grid">
        <div v-for="item in goodsList" :key="item.id" class="goods-item" @click="goToDetail(item.id)">
          <img :src="item.image || '@/assets/default-goods.png'" alt="" class="goods-img" />
          <h4>{{ item.name }}</h4>
          <p>¥{{ item.price }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import goodsApi from '@/api/goods_api.js'
import { useRoute, useRouter } from 'vue-router'
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElButton } from 'element-plus'

export default {
  name: 'GoodsListPage',
  components: {
    Search,
    ArrowLeft,
    ElButton
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const goodsList = ref([])
    const loading = ref(false)
    const error = ref('')
    const searchKeyword = ref('')

    // 获取商品列表
    const fetchGoods = async (keyword) => {
      loading.value = true
      error.value = ''
      try {
        console.log('搜索关键词:', keyword)

        // 只传递 name 参数进行模糊搜索
        const params = {
          name: keyword
        }

        const res = await goodsApi.getGoodsList(params)
        console.log('API返回结果:', res)

        if (res || res.code === 200) {
          // 确保 data 是数组
          if (Array.isArray(res)) {
            goodsList.value = [...res] // 创建新数组确保响应式更新
            console.log('设置商品列表:', goodsList.value)
            console.log('商品数量:', goodsList.value.length)
          } else {
            goodsList.value = []
          }
        } else {
          error.value = '获取商品失败'
          goodsList.value = []
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试'
        goodsList.value = []
        console.error('获取商品列表失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 处理搜索
    const handleSearch = () => {
      if (searchKeyword.value.trim()) {
        // 更新路由参数但不重新加载页面
        router.push({
          name: 'goodsList',
          query: {keyword: searchKeyword.value.trim()}
        })
        fetchGoods(searchKeyword.value.trim())
      }
    }

    // 跳转到商品详情页
    const goToDetail = (id) => {
      router.push(`/user/goods-profile/${id}`)
    }

    // 返回到商品页面
    const goToShopping = () => {
      router.push({name: 'shopping'})
    }

    // 监听路由变化
    watch(() => route.query.keyword, (newKeyword) => {
      console.log('路由参数变化:', newKeyword)
      if (newKeyword) {
        searchKeyword.value = newKeyword
        fetchGoods(newKeyword)
      } else {
        searchKeyword.value = ''
        goodsList.value = []
      }
    })

    // 页面挂载时加载搜索结果
    onMounted(() => {
      // 获取路由参数中的搜索关键词
      const keyword = route.query.keyword
      console.log('初始路由参数:', keyword)
      if (keyword) {
        searchKeyword.value = keyword
        fetchGoods(keyword)
      }
    })

    return {
      goodsList,
      loading,
      error,
      searchKeyword,
      goToDetail,
      handleSearch,
      goToShopping
    }
  }
}
</script>

<style scoped>
.goods-list-page {
  background-color: #fff;
  padding: 20px;
}

.goods-list-page h2 {
  margin-bottom: 20px;
  color: #333;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
}

.back-button {
  height: 40px;
}

.search-input {
  flex: 1;
  max-width: 500px;
}

/* 商品列表容器 */
.goods-list-container {
  margin-top: 20px;
}

.loading, .error {
  text-align: center;
  padding: 20px;
  color: #999;
}

.empty {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 商品网格布局 - 修改为一行4个 */
.goods-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.goods-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.goods-item:hover {
  transform: translateY(-5px);
}

.goods-img {
  width: 100%;
  height: 250px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.goods-item h4 {
  margin: 10px 0;
  font-size: 16px;
  color: #333;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-item p {
  color: #e64340;
  font-weight: bold;
  font-size: 18px;
  margin: 10px 0;
}

@media (max-width: 1200px) {
  .goods-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .goods-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .search-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .back-button {
    margin-bottom: 10px;
  }
}

@media (max-width: 576px) {
  .goods-grid {
    grid-template-columns: 1fr;
  }

  .goods-item {
    padding: 10px;
  }

  .goods-img {
    height: 150px;
  }
}
</style>
